package algotithm.leetcode.array.test4;

/**
 * @author zhouyanxiang
 * @Date 2021-04-2021/4/4-23:14
 * @Title 4. 寻找两个正序数组的中位数
 */
public class Solution {

    public static void main(String[] args) {
        int[] nums1 = {1,3};
        int[] nums2 = {2};
        Solution solution = new Solution();
        double medianSortedArrays = solution.findMedianSortedArrays(nums1, nums2);
        System.out.println(medianSortedArrays);
    }

    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int m = nums1.length;
        int n = nums2.length;
        int len = m + n;
        int l = -1;
        int r = -1;
        int aStart = 0;
        int bStart = 0;
        for (int i = 0;i <= len / 2; i++) {
            l = r;
            if (aStart < m && (bStart >= n || (nums1[aStart] < nums2[bStart]))) {
                r = nums1[aStart++];
            } else {
                r = nums2[bStart++];
            }
        }
        if ((len & 1) == 0) {
            return (l + r) / 2.0;
        } else {
            return r;
        }
    }
}
